﻿Imports System.Data.SqlClient
Imports System.Drawing
Imports DevExpress.XtraGrid
Imports DevExpress.XtraGrid.Views.Base
Imports DevExpress.XtraGrid.Columns
Imports DevExpress.XtraEditors
Imports DevExpress.XtraScheduler
Imports DevExpress.XtraScheduler.UI
Imports DevExpress.XtraEditors.Controls
Public Class frmToolsLookUp
    Dim mstrMode As String
    Public blnAdd As Boolean, blnEdit As Boolean, blnDelete As Boolean, blnLocked As Boolean
    Dim mlngRecordID As Long
    Dim blnUnload As Boolean
    Dim mblnChanged As Boolean
    Dim mblnActivate As Boolean
    Dim mblnExpanded As Boolean = False
    Dim mblnAutoSize As Boolean = True
    Dim mblnCancelDisplay As Boolean
    Public mblnFrmOtherForm As Boolean
    Public mstrLookUpValue As String
    Public mstrItemName As String
    Public mintGrbId As Integer      ' for setting value into respective text boxes from entry form. 1- grbOnecontrol, 2- grbTwoControl, 3-Diagnosis


    Private Sub frmToolsLookUp_Activated(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Activated
        Try
            If mblnActivate = True Then
                mblnActivate = False

                pbRecords.Visible = True
                pbRecords.BringToFront()
                Application.DoEvents()
                pbRecords.Position = 20
                Call PopulateData()
                pbRecords.Position = 100
                pbRecords.Visible = False
                grdRecords.Focus()
                If mblnFrmOtherForm = True Then
                    lkLookUp.EditValue = mstrLookUpValue
                    btnAdd_Click(Nothing, Nothing)
                    If mintGrbId = 1 Then

                        If mstrItemName = "" Then
                            txtItemName.Focus()
                        Else
                            txtItemName.Text = mstrItemName
                            btnSave.Focus()
                        End If

                    ElseIf mintGrbId = 2 Then

                        If mstrItemName = "" Then
                            txtTownParishName.Focus()
                        Else
                            txtTownParishName.Text = mstrItemName
                            lkOther.Focus()
                        End If

                    ElseIf mintGrbId = 3 Then

                        If mstrItemName = "" Then
                            txtDiagnosisText.Focus()
                        Else
                            txtDiagnosisText.Text = mstrItemName
                            txtDiagnosisNo.Focus()
                        End If

                    End If


                End If
            End If

        Catch ex As Exception
            pbRecords.Visible = False
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub


    Private Sub frmToolsLookUp_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        Try

            Dim intUnload As DialogResult

            If mblnChanged = True And mstrMode <> "" Then
                intUnload = MessageBox.Show("You have not saved your changes to the record. Do you want to save your changes now?", gstrMessage, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1)
                If intUnload = Windows.Forms.DialogResult.Cancel Then
                    e.Cancel = True : Exit Sub
                ElseIf intUnload = Windows.Forms.DialogResult.Yes Then
                    blnUnload = True
                    If blnSaveRecords() = False Then
                        e.Cancel = True
                        blnUnload = False
                        Exit Sub
                    End If
                    mblnChanged = False
                End If
            End If
            blnUnload = False

        Catch ex As Exception
            blnUnload = False
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub


    Private Sub frmToolsLookUp_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
        mblnCancelDisplay = True
        If blnKeyTrap(e.KeyCode, Me, True, grdRecords) = True Then mblnCancelDisplay = False : Exit Sub
        mblnCancelDisplay = False

        If e.KeyCode = Keys.F5 Then
            gdvRecords_FocusedRowChanged(Nothing, Nothing)
        End If

        pbRecords.Visible = False
    End Sub


    Private Sub frmToolsLookUp_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try

            Call SetImageControl(Me)
            Me.Icon = System.Drawing.Icon.FromHandle(CType(mdiMain.imgFormIcons.Images(2), Bitmap).GetHicon())
            Call btnExpand_Click(Me, e)
            Call GetAccessPermission(Me, "frmToolsLookUp")
            Call PopulateLookUpValues()
            Call setPBRecords(Me, pbRecords)
            mblnActivate = True
            mblnChanged = False

        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Public Sub PopulateData()
        Dim dsRecords As DataSet   'For populating data in XtraGrid
        Dim strQuery As String = ""
        Try
            pbRecords.Position = 40 : Application.DoEvents()
            If lkLookUp.EditValue = "LtblParish" Then
                strQuery = "SELECT LtblParish.ParishId, LtblParish.Parish, LtblParish.CountryId, LtblCountry.Country FROM  LtblParish INNER JOIN LtblCountry ON LtblParish.CountryId = LtblCountry.CountryId"
            ElseIf lkLookUp.EditValue = "LtblTown" Then
                strQuery = "SELECT  LtblTown.TownId, LtblTown.Town, LtblTown.ParishId, LtblParish.Parish  FROM LtblParish INNER JOIN  LtblTown ON LtblParish.ParishId = LtblTown.ParishId"
            Else
                strQuery = "Select * from " & lkLookUp.EditValue 'tableName
            End If
            dsRecords = FillDataSet(strQuery)

            gdvRecords.Columns.Clear()

            With grdRecords
                .BeginUpdate()
                .DataSource = dsRecords.Tables(0)
                .EndUpdate()
            End With
            dsRecords.Dispose()

            With gdvRecords
                'Primary Key Field
                .Columns(0).Visible = False
                .Appearance.Row.Font = New Font("Tahoma", 10, FontStyle.Regular)
                .OptionsCustomization.AllowQuickHideColumns = False
                .OptionsView.RowAutoHeight = True
                .BestFitColumns()

                If (.Columns.Contains(.Columns.ColumnByFieldName("CountryId"))) Then
                    .Columns("CountryId").Visible = False
                End If
                If (.Columns.Contains(.Columns.ColumnByFieldName("Sortorder"))) Then
                    .Columns("Sortorder").Visible = False
                End If
                If (.Columns.Contains(.Columns.ColumnByFieldName("DiagnosisGroupId"))) Then
                    .Columns("DiagnosisGroupId").Visible = False
                End If

                If (.Columns.Contains(.Columns.ColumnByFieldName("ParishId"))) Then
                    .Columns("ParishId").Visible = False
                End If

                If (.Columns.Contains(.Columns.ColumnByFieldName("CauseId"))) Then
                    .Columns("CauseId").Visible = False
                End If

                If (.Columns.Contains(.Columns.ColumnByFieldName("AppointmentTime"))) Then
                    .Columns("AppointmentTime").DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime
                    .Columns("AppointmentTime").DisplayFormat.FormatString = "hh:mm:ss tt"
                End If
                .BestFitColumns()
            End With
            pbRecords.Position = 80 : Application.DoEvents()
            'To set row count
            gdvRecords_ColumnFilterChanged(Nothing, Nothing)
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub


    Private Sub btnExpand_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExpand.Click
        If mblnExpanded = True Then
            mblnExpanded = False
            btnExpand.Image = mdiMain.imgEditIcons.Images(0)
            grdRecords.Width = 197
            Call btnCancel_Click(Nothing, Nothing)

        Else
            mblnExpanded = True
            btnExpand.Image = mdiMain.imgEditIcons.Images(1)
            grdRecords.Width = 587 : grdRecords.BringToFront()
            If gdvRecords.RowCount > 0 Then mlngRecordID = gdvRecords.GetRowCellValue(gdvRecords.FocusedRowHandle, gdvRecords.Columns(0).FieldName)
        End If
        If mblnAutoSize = True Then
            gdvRecords.OptionsView.ColumnAutoWidth = (mblnExpanded = True)
        End If

        grdRecords.Focus()
    End Sub

    Private Sub DisplayData()
        Dim dsTemp As DataSet

        Try

            dsTemp = FillDataSet("select * from " & lkLookUp.EditValue & " where " & gdvRecords.Columns(0).FieldName & " =" & mlngRecordID)
            With dsTemp.Tables(0)
                If .Rows.Count > 0 Then
                    If lkLookUp.EditValue <> "LtblDiagnosis" AndAlso lkLookUp.EditValue <> "LtblTown" AndAlso lkLookUp.EditValue <> "LtblParish" AndAlso lkLookUp.EditValue.SubString(0, 7) <> "LtblROS" Then
                        txtItemName.Text = Trim(.Rows(0).Item(1))
                    ElseIf lkLookUp.EditValue = "LtblTown" Or lkLookUp.EditValue = "LtblParish" Then
                        txtTownParishName.Text = .Rows(0).Item(1)
                        lkOther.EditValue = CInt(.Rows(0).Item(2))
                    ElseIf lkLookUp.EditValue.Substring(0, 7) = "LtblROS" Then
                        txtTownParishName.Text = .Rows(0).Item(1)
                        txtSortOrder.Text = .Rows(0).Item(2)
                    ElseIf lkLookUp.EditValue = "LtblDiagnosis" Then
                        txtDiagnosisText.Text = .Rows(0).Item(1)
                        txtDiagnosisNo.Text = Trim(.Rows(0).Item(3) & "")
                        lkDiagnosisGroup.EditValue = CInt(.Rows(0).Item(2))
                    End If
                End If
            End With
            dsTemp.Dispose()
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub


    Private Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Call EnableDisableControls(True)

        If mstrMode = "Add" Then
            If gdvRecords.RowCount > 0 Then
                mlngRecordID = gdvRecords.GetRowCellValue(gdvRecords.FocusedRowHandle, gdvRecords.Columns(0).FieldName)
                DisplayData()
            Else
                ClearControls()
                btnEdit.Enabled = False : btnDelete.Enabled = False : btnPreview.Enabled = False
            End If
        Else
            If gdvRecords.RowCount = 0 Then
                ClearControls()
                btnEdit.Enabled = False : btnDelete.Enabled = False : btnPreview.Enabled = False
            Else
                DisplayData()
            End If
        End If
        Call visibleinvisible_Controls()
        'grbOneControl.BackColor = grbControls.BackColor
        'grbTwoControls.BackColor = grbControls.BackColor
        'grbDiagnosis.BackColor = grbControls.BackColor
        Me.Text = "Drop-down Parameters"
        mstrMode = ""
        mblnChanged = False
    End Sub

    Private Sub EnableDisableControls(ByVal blnEnable As Boolean)
        If blnAdd = True Then btnAdd.Enabled = blnEnable
        If blnEdit = True Then btnEdit.Enabled = blnEnable
        If blnDelete = True Then btnDelete.Enabled = blnEnable
        btnPreview.Enabled = blnEnable

        btnSave.Enabled = Not (blnEnable) : btnCancel.Enabled = Not (blnEnable)
        lkLookUp.Enabled = blnEnable
        grbControls.Enabled = Not (blnEnable)
        Call visibleinvisible_Controls()
    End Sub


    Private Sub gdvRecords_ColumnFilterChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles gdvRecords.ColumnFilterChanged
        gdvRecords.Columns(1).SummaryItem.SetSummary(DevExpress.Data.SummaryItemType.Count, "Total {0} Record(s)")

        Dim lngTemp As Long = lngGetSelectID(gdvRecords)
        If mlngRecordID <> lngTemp Or btnCancel.Enabled = True Then
            gdvRecords_FocusedRowChanged(Nothing, Nothing)
        End If
    End Sub


    'Private Sub gdvRecords_CustomDrawRowIndicator(ByVal sender As Object, ByVal e As DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs) Handles gdvRecords.CustomDrawRowIndicator
    '    SetRowIndicator(e)
    'End Sub


    Private Sub gdvRecords_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles gdvRecords.DoubleClick
        If btnEdit.Enabled = True Then
            Call btnEdit_Click(Nothing, Nothing)
        End If
    End Sub

    Private Sub gdvRecords_FocusedRowChanged(ByVal sender As Object, ByVal e As DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs) Handles gdvRecords.FocusedRowChanged
        Try
            If mblnCancelDisplay = True Then Exit Sub

            ' mlngRecordID = gdvRecords.GetRowCellValue(gdvRecords.FocusedRowHandle, gdvRecords.Columns(0).FieldName)
            mlngRecordID = lngGetSelectID(gdvRecords, gdvRecords.Columns(0).FieldName)
            If gdvRecords.RowCount > 0 Then
                btnEdit.Enabled = blnEdit : btnDelete.Enabled = blnDelete
                btnPreview.Enabled = True
            Else
                ClearControls()
                btnEdit.Enabled = False : btnDelete.Enabled = False : btnPreview.Enabled = False
            End If
            btnAdd.Enabled = blnAdd

            If mlngRecordID = 0 Then Exit Sub

            If mblnExpanded = True Then Exit Sub

            Call btnCancel_Click(Nothing, Nothing)

        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub


    Private Sub gdvRecords_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles gdvRecords.GotFocus
        If btnCancel.Enabled = True And Me.Visible = True Then Call btnCancel_Click(Nothing, Nothing)
    End Sub

    Private Sub gdvRecords_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles gdvRecords.KeyDown
        Try

            If e.KeyCode = Keys.Delete And btnDelete.Enabled = True Then
                Call btnDelete_Click(Nothing, Nothing)
            ElseIf e.KeyCode = Keys.Return And btnDelete.Enabled = True Then
                Call gdvRecords_DoubleClick(Nothing, Nothing)
            ElseIf e.KeyCode = Keys.Escape Then
                Call btnClose_Click(Nothing, Nothing)
            End If

        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub


    Private Sub btnClose_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnClose.Click
        'If mblnActivate = False Then
        '    If mblnExpanded = False Then btnExpand_Click(Nothing, Nothing) Else Me.Close()
        'End If
        Me.Close()
    End Sub


    Public Sub btnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAdd.Click
        Try
            If mblnExpanded = True Then btnExpand_Click(Nothing, Nothing)
            Call EnableDisableControls(False)
            Call ClearControls()
            mstrMode = "Add"
            mlngRecordID = 0
            Me.Text = "Drop-down Parameters [Add]"
            If grbOneControl.Visible = True Then
                txtItemName.Focus()
                txtItemName.Text = ""
            ElseIf grbTwoControls.Visible = True Then
                txtTownParishName.Focus()
            ElseIf grbDiagnosis.Visible = True Then
                txtDiagnosisText.Focus()
            End If
            mblnChanged = False
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Function blnSaveRecords() As Boolean
        Dim blnIsTransactionOpen As Boolean
        Dim strQuery As String = ""
        Try
            blnSaveRecords = False
            If lkLookUp.EditValue <> "LtblDiagnosis" AndAlso lkLookUp.EditValue <> "LtblTown" AndAlso lkLookUp.EditValue <> "LtblParish" AndAlso lkLookUp.EditValue.SubString(0, 7) <> "LtblROS" Then
                If IsDBNullOrNothing(txtItemName.Text) Then
                    MessageBox.Show("Specify " & lblItemName.Text, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                    txtItemName.Focus()
                    Exit Function
                End If
            ElseIf lkLookUp.EditValue = "LtblTown" Or lkLookUp.EditValue = "LtblParish" Then
                If IsDBNullOrNothing(txtTownParishName.Text) Then
                    MessageBox.Show("Specify " & lblMain.Text, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                    txtTownParishName.Focus()
                    Exit Function
                ElseIf IsDBNullOrNothing(lkOther.EditValue) Then
                    MessageBox.Show("Specify " & lblOther.Text, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                    lkOther.Focus()
                    Exit Function
                End If
            ElseIf lkLookUp.EditValue.SubString(0, 7) = "LtblROS" Then
                If IsDBNullOrNothing(txtTownParishName.Text) Then
                    MessageBox.Show("Specify " & lblMain.Text, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                    txtTownParishName.Focus()
                    Exit Function
                ElseIf IsDBNullOrNothing(txtSortOrder.Text) Then
                    MessageBox.Show("Specify " & lblOther.Text, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                    lkOther.Focus()
                    Exit Function
                ElseIf Val(txtSortOrder.EditValue) <= 0 Then
                    MessageBox.Show("Please enter proper sort order", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                    txtSortOrder.Focus()
                    Exit Function
                End If
            ElseIf lkLookUp.EditValue = "LtblDiagnosis" Then
                If IsDBNullOrNothing(txtDiagnosisText.Text) Then
                    MessageBox.Show("Specify diagnosis", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                    txtDiagnosisText.Focus()
                    Exit Function
                ElseIf IsDBNullOrNothing(lkDiagnosisGroup.EditValue) Then
                    MessageBox.Show("Specify diagnosis group", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                    lkDiagnosisGroup.Focus()
                    Exit Function
                End If
            End If
            If (blnUnload = False) Then
                If (MessageBox.Show("Are you sure to " & IIf(mstrMode = "Add", "add", "modify") & " this " & lkLookUp.Text.ToString, "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = System.Windows.Forms.DialogResult.No) Then
                    Exit Function
                End If
            End If

            gtrnWebPlusMed = gconWebPlusMed.BeginTransaction
            blnIsTransactionOpen = True

            If mstrMode = "Add" Then
                If lkLookUp.EditValue <> "LtblDiagnosis" AndAlso lkLookUp.EditValue <> "LtblTown" AndAlso lkLookUp.EditValue <> "LtblParish" AndAlso lkLookUp.EditValue.SubString(0, 7) <> "LtblROS" Then

                    strQuery = "'" & Replace(Trim(txtItemName.Text), "'", "''") & "'"
                ElseIf lkLookUp.EditValue = "LtblTown" Or lkLookUp.EditValue = "LtblParish" Then
                    strQuery = "'" & Replace(Trim(txtTownParishName.Text), "'", "''") & "'"
                    strQuery = strQuery & "," & Val(lkOther.EditValue)
                ElseIf lkLookUp.EditValue.SubString(0, 7) = "LtblROS" Then
                    strQuery = "'" & Replace(Trim(txtTownParishName.Text), "'", "''") & "'"
                    strQuery = strQuery & "," & Val(txtSortOrder.Text)
                ElseIf lkLookUp.EditValue = "LtblDiagnosis" Then
                    strQuery = "'" & Replace(Trim(txtDiagnosisText.Text), "'", "''") & "'"
                    strQuery = strQuery & "," & Val(lkDiagnosisGroup.EditValue)
                    If IsDBNullOrNothing(txtDiagnosisNo.Text) Then
                        strQuery = strQuery & ",Null"
                    Else
                        strQuery = strQuery & ",'" & Replace(Trim(txtDiagnosisNo.Text), "'", "''") & "'"
                    End If
                End If
                Call InsertintoTable(lkLookUp.EditValue, strQuery)
            ElseIf mstrMode = "Edit" Then
                If lkLookUp.EditValue <> "LtblDiagnosis" AndAlso lkLookUp.EditValue <> "LtblTown" AndAlso lkLookUp.EditValue <> "LtblParish" AndAlso lkLookUp.EditValue.SubString(0, 7) <> "LtblROS" Then
                    strQuery = gdvRecords.Columns(1).FieldName & "='" & Replace(Trim(txtItemName.Text), "'", "''") & "'"
                ElseIf lkLookUp.EditValue = "LtblTown" Or lkLookUp.EditValue = "LtblParish" Then
                    strQuery = gdvRecords.Columns(1).FieldName & "='" & Replace(Trim(txtTownParishName.Text), "'", "''") & "'"
                    strQuery = strQuery & "," & gdvRecords.Columns(2).FieldName & "=" & Val(lkOther.EditValue)
                ElseIf lkLookUp.EditValue.SubString(0, 7) = "LtblROS" Then
                    strQuery = gdvRecords.Columns(1).FieldName & "='" & Replace(Trim(txtTownParishName.Text), "'", "''") & "'"
                    strQuery = strQuery & "," & gdvRecords.Columns(2).FieldName & "=" & Val(txtSortOrder.Text)
                ElseIf lkLookUp.EditValue = "LtblDiagnosis" Then
                    strQuery = gdvRecords.Columns(1).FieldName & "='" & Replace(Trim(txtDiagnosisText.Text), "'", "''") & "'"
                    strQuery = strQuery & "," & gdvRecords.Columns(2).FieldName & "=" & Val(lkDiagnosisGroup.EditValue)
                    If IsDBNullOrNothing(txtDiagnosisNo.Text) Then
                        strQuery = strQuery & "," & gdvRecords.Columns(3).FieldName & "=Null"
                    Else
                        strQuery = strQuery & "," & gdvRecords.Columns(3).FieldName & "='" & Replace(Trim(txtDiagnosisNo.Text), "'", "''") & "'"
                    End If
                End If
                Call UpdateTable(lkLookUp.EditValue, strQuery, gdvRecords.Columns(0).FieldName & "=" & mlngRecordID)
            End If

            blnSaveRecords = True

            gtrnWebPlusMed.Commit()
            blnIsTransactionOpen = False

        Catch ex As Exception
            If blnIsTransactionOpen = True Then
                gtrnWebPlusMed.Rollback()
            End If
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Function


    Private Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
        Dim lngTemp As Long, lngRowID As Long

        Try
            If mblnChanged = False Then
                Call btnCancel_Click(Nothing, Nothing)
                Exit Sub
            End If

            If blnSaveRecords() = False Then Exit Sub
            If mstrMode = "Add" Then
                mlngRecordID = GetId(lkLookUp.EditValue)
            End If

            lngTemp = mlngRecordID

            pbRecords.Visible = True
            pbRecords.BringToFront()
            Application.DoEvents()
            pbRecords.Position = 20

            gdvRecords.OptionsSelection.EnableAppearanceFocusedRow = False
            gdvRecords.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.None
            mblnCancelDisplay = True
            Call PopulateData()
            mblnCancelDisplay = False

            pbRecords.Position = 95
            If gdvRecords.RowCount > 0 Then
                lngRowID = LocateRowBySingleValue(grdRecords, lngTemp)
                gdvRecords.FocusedRowHandle = lngRowID
                If lngRowID = 0 Then gdvRecords_FocusedRowChanged(Nothing, Nothing)
            Else
                Call btnCancel_Click(Nothing, Nothing)
            End If
            gdvRecords.OptionsSelection.EnableAppearanceFocusedRow = True
            gdvRecords.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.RowFocus

            pbRecords.Position = 100
            pbRecords.Visible = False

            If mblnFrmOtherForm = True Then
                mlngLookUpId = mlngRecordID
                Me.Close()
            End If

        Catch ex As Exception
            pbRecords.Visible = False
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub


    Private Sub btnPreview_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPreview.Click
        ShowGridPreview(grdRecords, Me.Text)
    End Sub


    Private Sub btnEdit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnEdit.Click
        Try
            If mblnExpanded = True Then btnExpand_Click(Nothing, Nothing)

            Call EnableDisableControls(False)
            mblnChanged = False
            mstrMode = "Edit"
            Me.Text = "Drop-down Parameters [Edit]"

        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub


    Private Sub gdvRecords_ShowGridMenu(ByVal sender As Object, ByVal e As DevExpress.XtraGrid.Views.Grid.GridMenuEventArgs) Handles gdvRecords.ShowGridMenu
        If e.MenuType = DevExpress.XtraGrid.Views.Grid.GridMenuType.Column Then
            Dim mainMenu As DevExpress.XtraGrid.Menu.ViewMenu = CType(e.Menu, DevExpress.XtraGrid.Menu.ViewMenu)
            Dim mainItem As New DevExpress.Utils.Menu.DXMenuItem("Column Auto Width", New EventHandler(AddressOf MainMenuItem))
            mainItem.BeginGroup = True
            mainItem.Tag = e.Menu
            mainMenu.Items.Add(mainItem)
            mainItem.Image = IIf(mblnAutoSize = True, mdiMain.imgEditIcons.Images(13), Nothing)
        End If
    End Sub

    Private Sub MainMenuItem(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim Item As DevExpress.Utils.Menu.DXMenuItem = CType(sender, DevExpress.Utils.Menu.DXMenuItem)
        Dim menu As DevExpress.XtraGrid.Menu.GridViewMenu = CType(Item.Tag, DevExpress.XtraGrid.Menu.GridViewMenu)
        mblnAutoSize = Not (mblnAutoSize)
        gdvRecords.OptionsView.ColumnAutoWidth = (mblnAutoSize = True)
        If gdvRecords.OptionsView.ColumnAutoWidth = False Then gdvRecords.BestFitColumns()
    End Sub

    Public Sub SetRowFromOutside(ByVal RecID As Long)
        Dim lngRowID As Long
        gdvRecords.OptionsSelection.EnableAppearanceFocusedRow = False
        gdvRecords.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.None
        lngRowID = LocateRowBySingleValue(grdRecords, RecID)
        gdvRecords.FocusedRowHandle = lngRowID
        If lngRowID = 0 Then gdvRecords_FocusedRowChanged(Nothing, Nothing)
        gdvRecords.OptionsSelection.EnableAppearanceFocusedRow = True
        gdvRecords.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.RowFocus
    End Sub

    Private Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click
        Dim blnTrnasaction As Boolean

        Try

            If MessageBox.Show("Are you sure you want to permanently delete this record", gstrMessage, MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
                gtrnWebPlusMed = gconWebPlusMed.BeginTransaction
                blnTrnasaction = True
                Call DeleteFromTable(lkLookUp.EditValue, gdvRecords.Columns(0).FieldName & "=" & mlngRecordID)
                gtrnWebPlusMed.Commit()
                blnTrnasaction = False
                MessageBox.Show("Record deleted", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Information)
                SendKeys.Send("{F5}")
            End If


        Catch ex As Exception
            If blnTrnasaction = True Then
                gtrnWebPlusMed.Rollback()
            End If
            MessageBox.Show("Record in use" & vbCrLf & "Cannot delete", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub PopulateLookUpValues()
        Dim strQuery As String
        Dim dsTemp As DataSet
        Dim intCtr As Integer
        strQuery = "select name AS TableName,SUBSTRING(name,5,LEN(name)-4) as [Lookup Name] from sysobjects where  name LIKE 'L%' ORDER BY [Lookup Name]"
        dsTemp = FillDataSet(strQuery)
        With lkLookUp.Properties
            .Columns.Clear()
            For intCtr = 0 To dsTemp.Tables(0).Rows.Count - 1
                If dsTemp.Tables(0).Rows(intCtr).Item("Lookup Name") = "ROSCNS" Then 'Or dsTemp.Tables(0).Rows(intCtr).Item("Lookup Name") = "ROSCVS" Or dsTemp.Tables(0).Rows(intCtr).Item("Lookup Name") = "ROSGI" Or dsTemp.Tables(0).Rows(intCtr).Item("Lookup Name") = "ROSGU" Or dsTemp.Tables(0).Rows(intCtr).Item("Lookup Name") = "ROSRS" Then
                    dsTemp.Tables(0).Rows(intCtr).Item("Lookup Name") = "Review Of System CNS"
                ElseIf dsTemp.Tables(0).Rows(intCtr).Item("Lookup Name") = "ROSCVS" Then
                    dsTemp.Tables(0).Rows(intCtr).Item("Lookup Name") = "Review Of System CVS"
                ElseIf dsTemp.Tables(0).Rows(intCtr).Item("Lookup Name") = "ROSGI" Then
                    dsTemp.Tables(0).Rows(intCtr).Item("Lookup Name") = "Review Of System GI"
                ElseIf dsTemp.Tables(0).Rows(intCtr).Item("Lookup Name") = "ROSGU" Then
                    dsTemp.Tables(0).Rows(intCtr).Item("Lookup Name") = "Review Of System GU"
                ElseIf dsTemp.Tables(0).Rows(intCtr).Item("Lookup Name") = "ROSRS" Then
                    dsTemp.Tables(0).Rows(intCtr).Item("Lookup Name") = "Review Of System RS"
                Else
                    Dim str As String = dsTemp.Tables(0).Rows(intCtr).Item("Lookup Name")
                    Dim SB As New System.Text.StringBuilder
                    For Each Chr As Char In str
                        If Char.IsUpper(Chr) Then
                            SB.Append(" ")
                        End If
                        SB.Append(Chr)
                    Next
                    dsTemp.Tables(0).Rows(intCtr).Item("Lookup Name") = LTrim(SB.ToString)
                End If

            Next
            .DataSource = dsTemp.Tables(0)
            .DisplayMember = "Lookup Name"
            .ValueMember = "TableName"
            'Add columns to the dropdown.

            Dim coll As LookUpColumnInfoCollection = .Columns
            For intCtr = 1 To 2
                'Dim str As String = dsTemp.Tables(0).Columns(intCtr - 1).Caption
                'Dim SB As New System.Text.StringBuilder
                'For Each Chr As Char In str
                '    If Char.IsUpper(Chr) Then
                '        SB.Append(" ")
                '    End If
                '    SB.Append(Chr)
                'Next
                coll.Add(New LookUpColumnInfo(dsTemp.Tables(0).Columns(intCtr - 1).Caption, 0))
                'coll.Add(New LookUpColumnInfo(SB.ToString, 0))
            Next
            'Set column widths according to their contents.
            .BestFit()
            'Specify the total dropdown width.
            .PopupWidth = 200
            'Enable auto completion search mode.
            .SearchMode = SearchMode.AutoComplete
            'Specify the column against which to perform the search.
            .AutoSearchColumnIndex = 1
            .Columns(0).Visible = False 'ID field
            .ShowFooter = False
            .Columns("TableName").Visible = False
        End With
        lkLookUp.EditValue = dsTemp.Tables(0).Rows(0).Item("TableName")
        dsTemp.Dispose()

    End Sub


    Private Sub lkLookUp_ButtonClick(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.Controls.ButtonPressedEventArgs) Handles lkLookUp.ButtonClick
        If e.Button.Index = 1 Then
            Call PopulateLookUpValues()
        End If
    End Sub


    Private Sub lkLookUp_EditValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles lkLookUp.EditValueChanged
        If Not IsDBNullOrNothing(lkLookUp.EditValue) Then
            Call PopulateData()
        End If
    End Sub
    Private Sub visibleinvisible_Controls()
        If lkLookUp.EditValue <> "LtblDiagnosis" AndAlso lkLookUp.EditValue <> "LtblTown" AndAlso lkLookUp.EditValue <> "LtblParish" AndAlso lkLookUp.EditValue.SubString(0, 7) <> "LtblROS" Then
            grbOneControl.Visible = True
            grbDiagnosis.Visible = False
            grbTwoControls.Visible = False
            grbOneControl.Text = lkLookUp.Text.ToString
            lblItemName.Text = lkLookUp.Text.ToString

        ElseIf lkLookUp.EditValue = "LtblTown" Or lkLookUp.EditValue = "LtblParish" Or lkLookUp.EditValue.SubString(0, 7) = "LtblROS" Then
            grbOneControl.Visible = False
            grbDiagnosis.Visible = False
            grbTwoControls.Visible = True
            grbTwoControls.Text = lkLookUp.Text.ToString
            If lkLookUp.EditValue = "LtblTown" Then
                grbTwoControls.Text = "Town"
                lblMain.Text = "Town Name"
                lblOther.Text = "Parish Name"
                txtSortOrder.Visible = False
                lkOther.Visible = True
                Call PopulateLookupDX(lkOther, "Parish", "ParishId", "LtblParish", "ParishId,Parish", , "Parish")
            ElseIf lkLookUp.EditValue = "LtblParish" Then
                lblMain.Text = "Parish Name"
                lblOther.Text = "Country Name"
                txtSortOrder.Visible = False
                lkOther.Visible = True
                Call PopulateLookupDX(lkOther, "Country", "CountryId", "ltblCountry", "CountryId,Country", , "Country")
            ElseIf lkLookUp.EditValue.Substring(0, 7) = "LtblROS" Then
                lblMain.Text = "ROS Text"
                lblOther.Text = "Sort Order"
                txtSortOrder.Location = lkOther.Location
                txtSortOrder.Visible = True
                lkOther.Visible = False
            End If
        ElseIf lkLookUp.EditValue = "LtblDiagnosis" Then
            grbOneControl.Visible = False
            grbDiagnosis.Visible = True
            grbDiagnosis.BringToFront()
            grbTwoControls.Visible = False
            grbDiagnosis.Text = lkLookUp.Text.ToString
            Call PopulateLookupDX(lkDiagnosisGroup, "DiagnosisGroup", "DiagnosisGroupID", "LtblDiagnosisGroup", "DiagnosisGroupID,DiagnosisGroup", , "DiagnosisGroup")
        End If
    End Sub

    Private Sub ClearControls()
        Try
            Call Clearfields(grbControls)
            Call Clearfields(grbDiagnosis)
            Call Clearfields(grbTwoControls)
            Call Clearfields(grbOneControl)
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub lkDiagnosisGroup_ButtonClick(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.Controls.ButtonPressedEventArgs) Handles lkDiagnosisGroup.ButtonClick
        If e.Button.Index = 1 Then
            Call PopulateLookupDX(lkDiagnosisGroup, "DiagnosisGroup", "DiagnosisGroupID", "LtblDiagnosisGroup", "DiagnosisGroupID,DiagnosisGroup", , "DiagnosisGroup")
        End If
    End Sub

    Private Sub lkDiagnosisGroup_EditValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles lkDiagnosisGroup.EditValueChanged
        If IsDBNullOrNothing(lkDiagnosisGroup.EditValue) = False Then
            mblnChanged = True
        End If
    End Sub

    Private Sub lkOther_ButtonClick(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.Controls.ButtonPressedEventArgs) Handles lkOther.ButtonClick
        If e.Button.Index = 1 Then
            If lkLookUp.EditValue = "LtblTown" Then
                Call PopulateLookupDX(lkOther, "Parish", "ParishId", "LtblParish", "ParishId,Parish", , "Parish")
            ElseIf lkLookUp.EditValue = "LtblParish" Then
                Call PopulateLookupDX(lkOther, "Country", "CountryId", "ltblCountry", "CountryId,Country", , "Country")
            End If

        End If
    End Sub

    Private Sub lkOther_EditValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles lkOther.EditValueChanged
        If IsDBNullOrNothing(lkOther.EditValue) = False Then
            mblnChanged = True
        End If
    End Sub

    Private Sub txtDiagnosisNo_EditValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtDiagnosisNo.EditValueChanged
        mblnChanged = True
    End Sub

    Private Sub txtDiagnosisText_EditValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtDiagnosisText.EditValueChanged
        mblnChanged = True
    End Sub

    Private Sub txtItemName_EditValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtItemName.EditValueChanged
        mblnChanged = True
    End Sub

    Private Sub txtSortOrder_EditValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtSortOrder.EditValueChanged
        mblnChanged = True
    End Sub

    Private Sub txtTownParishName_EditValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtTownParishName.EditValueChanged
        mblnChanged = True
    End Sub

    Private Sub txtDiagnosisNo_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtDiagnosisNo.GotFocus, txtDiagnosisText.GotFocus, txtItemName.GotFocus, txtSortOrder.GotFocus, txtTownParishName.GotFocus
        sender.selectall()
    End Sub

End Class